package com.leonzx.base.config.pager;

import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Created by liang on 2016/10/8.
 */
public class PageInterceptor {
    public PageInterceptor() {
    }
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
        Page page = null;
        Object[] args = pjp.getArgs();
        boolean pageable = true;
        int pageSize = 10;
        String pageOrderBy = "";
        String pageOrderDiv = Page.Sort.DESC;

        Object[] object = args;
        int var7 = args.length;
        for (int var8 = 0; var8 < var7; ++var8) {
            Object arg = object[var8];
            //去除分页参数注解，得到参数信息
            if (arg instanceof Page) {
                Method method = ((MethodSignature) pjp.getSignature()).getMethod();
                Annotation[][] ass = method.getParameterAnnotations();

                for (int i = 0; i < ass.length; ++i) {
                    for (int j = 0; j < ass[i].length; ++j) {
                        Annotation a = ass[i][j];
                        if (a instanceof PageInfo) {
                            PageInfo pageConfig = (PageInfo) a;
                            pageable = pageConfig.pageable();
                            pageSize = pageConfig.pageSize();
                            pageOrderBy = pageConfig.orderBy();
                            pageOrderDiv = pageConfig.orderDiv();
                        }
                    }
                }

                if (pageable) {
                    page = (Page) arg;
                    if (page.getRows() == 0) {
                        page.setRows(pageSize);
                    }
                    if (StringUtils.isBlank(page.getOrderBy())) {
                        page.setOrderBy(pageOrderBy);
                    }
                    if (StringUtils.isBlank(page.getOrderDir())) {
                        page.setOrderDir(pageOrderDiv);
                    }
                }
                break;
            }
        }
        if (page != null) {
            //开始物理分页查询
            PageHelper.startPage(page.getPage(), page.getRows());
            if (StringUtils.isNotBlank(page.getSortStr())) {
                PageHelper.orderBy(page.getSortStr());
            }
        }
        Object var16 = pjp.proceed();
        return var16;
    }
}